package org.example.interceptor;

import io.jsonwebtoken.Claims;
import org.example.dto.ShoppingUser;
import org.example.manage.ShoppingUserManage;
import org.example.manage.impl.ShoppingUserManageImpl;
import org.example.mapper.ShoppingUserMapper;
import org.example.rvo.ResultVO;
import org.example.util.JSONUtil;
import org.example.util.JWTUtil;
import org.example.util.TUserThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;
import java.util.UUID;

public class GetUserInterceptor implements HandlerInterceptor {

    @Resource
    private ShoppingUserManage shoppingUserManage;


    private final String PREFIX_KEY = "prefix:login:user:";
    private final String SUFFIX_KEY = "suffix:login:user:";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        request.setCharacterEncoding("utf8");
        response.setCharacterEncoding("utf8");

        String suffixToken = request.getHeader("suffixToken");
        if(suffixToken!= null){
            boolean b = JWTUtil.checkToken(suffixToken);
            //如果有效
            if(b){
                Claims claims = JWTUtil.parseJWT(suffixToken);
                Map<String,Object> claim = (Map)claims.get("user");
                ShoppingUser shoppingUser = new ShoppingUser();
                shoppingUser.setId((String) claim.get("id"));
                shoppingUser.setUserName((String)claim.get("userName"));
                shoppingUser.setUserGender((String)claim.get("userGender"));
                shoppingUser.setUserHeadimg((String)claim.get("userHeadImg"));
                shoppingUser.setUserPhone((String)claim.get("userPhone"));
                //如果在请求其他的时候，先判断后置token是不是过期，所以先拿出后置token中对应的用户id
                //然后绑定到对应的前置key中，判断前置key是不是存在
                String token = shoppingUserManage.getToken(SUFFIX_KEY + shoppingUser.getId());
                String prefixToken = shoppingUserManage.getToken(PREFIX_KEY + shoppingUser.getId());

                if(token == null){
                    PrintWriter out = response.getWriter();
                    out.write(JSONUtil.obj2str(ResultVO.failure("500","Token无效，请重新登录")));
                    out.close();
                    return false;
                }
                if(prefixToken != null && suffixToken.equalsIgnoreCase(token)){
                    TUserThreadLocal.set(shoppingUser);
                    return true;
                }
                if(prefixToken == null &&suffixToken.equalsIgnoreCase(token) ){
                    //前置没有了，但是后置还存在的情况
                    shoppingUserManage.addToken(PREFIX_KEY+ shoppingUser.getId(), UUID.randomUUID().toString().replaceAll("-",""),1500L);
                    shoppingUserManage.removeToken(SUFFIX_KEY+shoppingUser.getId());
                    shoppingUserManage.addToken(SUFFIX_KEY+shoppingUser.getId(),JWTUtil.createJWT(shoppingUser.getId(),shoppingUser,"login",1800*1000L),1800L);
                    TUserThreadLocal.set(shoppingUser);
                    return true;
                }
                if(prefixToken == null && !suffixToken.equalsIgnoreCase(token) ){
                    PrintWriter out = response.getWriter();
                //    shoppingUserManage.addToken(PREFIX_KEY+ shoppingUser.getId(), UUID.randomUUID().toString().replaceAll("-",""),1500L);
                 //   shoppingUserManage.removeToken(SUFFIX_KEY+shoppingUser.getId());
                 //   shoppingUserManage.addToken(SUFFIX_KEY+shoppingUser.getId(),JWTUtil.createJWT(shoppingUser.getId(),shoppingUser,"login",1800*1000L),1800L);
                    out.write(JSONUtil.obj2str(ResultVO.failure("500","Token无效，请重新登录")));
                    out.close();
                   return  false;
                }
            }
            PrintWriter out = response.getWriter();
            out.write(JSONUtil.obj2str(ResultVO.failure("500","Token无效，请重新登录")));
            out.close();
            return false;
        }
        PrintWriter out = response.getWriter();
        out.write(JSONUtil.obj2str(ResultVO.failure("500","Token无效，请重新登录")));
        out.close();
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            TUserThreadLocal.remove();
    }
}
